<template>
  <el-dialog
    v-el-drag-dialog
    :title="type === 'add' ? '新增保单' : '编辑保单'"
    :visible.sync="visible"
    width="700px"
    @closed="reset"
  >
    <el-form ref="dataForm" class="form" :rules="rules" :model="temp" label-position="right" label-width="100px">
      <el-form-item v-if="type==='add'" label-width="0" class="block">
        <el-input v-model.trim="text" placeholder="请输入" style="width: 90%;" @keyup.enter.native="e => searchCsm(e)">
          <el-select slot="prepend" v-model="textType" style="width: 100px;" placeholder="请选择">
            <el-option label="电话" value="csmRgPhone" />
            <el-option label="客户编号" value="csmCode" />
            <el-option label="身份证号" value="sfzh" />
          </el-select>
          <el-button slot="append" class="append-search" @click="e=>searchCsm(e)">查询</el-button>
        </el-input>
        <el-button @click="resetCsm">重置</el-button>
      </el-form-item>
      <el-form-item label="保单号:" prop="insureCode" class="block">
        <el-input v-model.trim="temp.insureCode" :maxlength="30" placeholder="请输入">
          <el-button v-if="type==='add'" slot="append" class="append-search" @click.prevent="getCode">获取</el-button>
        </el-input>
      </el-form-item>
      <el-form-item label="客户名称:" prop="csmName">
        <el-input v-model="temp.csmName" clearable />
      </el-form-item>
      <el-form-item label="投保地址:" prop="csmAddressId">
        <el-select v-model="temp.csmAddressId" placeholder="请选择">
          <el-option
            v-for="item in csmAddressList"
            :key="item.csmAddressId"
            :label="item.csmAddress"
            :value="item.csmAddressId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="投保金额:" prop="insureAcc">
        <el-input-number v-model="temp.insureAcc" :controls="false" :min="0" :max="99999" :precision="2" clearable style="width: 100%;" @blur="inputFormat" />
      </el-form-item>
      <el-form-item label="售保员:" prop="salePersonName">
        <el-input v-model="temp.salePersonName" :maxlength="11" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="生效日期:" prop="insureStartDt">
        <el-date-picker
          v-model="temp.insureStartDt"
          type="date"
          placeholder="选择日期"
          style="width: 100%;"
        />
      </el-form-item>
      <el-form-item label="截止日期:" prop="insureEndDt">
        <el-date-picker
          v-model="temp.insureEndDt"
          type="date"
          placeholder="选择日期"
          style="width: 100%;"
        />
      </el-form-item>
      <el-form-item label="备注:" prop="remark" class="block">
        <el-input v-model="temp.remark" type="textarea" :rows="3" maxlength="200" show-word-limit />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        关闭
      </el-button>
      <el-button :loading="$loadingPlugin.add || $loadingPlugin.edit" type="primary" @click="success">
        保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { queryCsmInfo, queryOrgCode, insureAdd, insureUpdate, queryCsmInfoById } from '@/api'
  import moment from 'dayjs'
  import { isWildPhone, isSfzh } from '@/utils'

  export default {
    name: 'add',
    data() {
      return {
        visible: false,
        type: 'add',
        text: '',
        textType: 'csmRgPhone',
        temp: {
          preInsureCode: '',
          insureCode: '',
          csmName: '',
          csmAddressId: '',
          insureAcc: undefined,
          salePersonName: '',
          insureStartDt: '',
          insureEndDt: '',
          remark: ''
        },
        row: {},
        rules: {
          insureCode: [{ required: true, message: '请输入保单号', trigger: 'change' }],
          csmName: [{ required: true, message: '请输入客户名称', trigger: 'change' }],
          insureStartDt: [{ required: true, message: '请输入保单生效日期', trigger: 'change' }],
          insureEndDt: [{ required: true, message: '请输入保单截止日期', trigger: 'change' }],
          insureAcc: [{ required: true, message: '请输入投保金额', trigger: 'change' }],
          csmAddressId: [{ required: true, message: '请输入投保地址', trigger: 'blur' }]
        },
        csmInfo: null,
        csmAddressList: []
      }
    },
    methods: {
      open(temp) {
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          if (temp) {
            this.temp = Object.assign(this.temp, temp, {
              preInsureCode: temp.insureCode
            })
            this.type = 'edit'
            this.row = temp
            if (temp.csmId) this.searchCsmById(temp.csmId)
          }
        })
      },
      // 获取编号
      async getCode() {
        const res = await queryOrgCode({
          codeType: 10
        })
        this.temp.insureCode = res.data
      },
      // 根据csmId查询客户信息
      async searchCsmById(csmId) {
        const res = await queryCsmInfoById({ csmId })
        this.csmInfo = res.data
        if (res.data.addressItems) this.csmAddressList = res.data.addressItems
        if (this.csmAddressList && this.csmAddressList.length === 1) {
          this.$set(this.temp, 'csmAddressId', this.csmAddressList[0].csmAddressId)
        }
      },
      // 查询客户
      async searchCsm(e, csmPhone) {
        if (this.type === 'add' && !this.text && !csmPhone) {
          this.$message.error('查询条件不允许为空')
          return
        }
        if (this.type === 'add' && this.textType === 'csmRgPhone') {
          if (!isWildPhone(this.text)) {
            this.$message.error('请输入正确的电话号码!')
            return
          }
          if (this.textType === 'sfzh') {
            if (!isSfzh(this.text)) {
              this.$message.error('身份证号格式不正确!')
              return
            }
          }
        }
        const params = {
          csmStatus: 9, // 查询状态不是已注销的客户
          pageIndex: 1,
          pageSize: 20
        }
        if (!csmPhone) params[this.textType] = this.text
        else params.csmRgPhone = csmPhone
        const res = await queryCsmInfo(params)
        this.$set(this.temp, 'csmName', '')
        this.$set(this.temp, 'csmAddressId', '')
        this.csmInfo = res.data
        if (res.data.addressItems) this.csmAddressList = res.data.addressItems
        this.$set(this.temp, 'csmName', res.data.csmName)
        if (this.csmAddressList && this.csmAddressList.length === 1) {
          if (e) this.$set(this.temp, 'csmAddressId', this.csmAddressList[0].csmAddressId)
        }
        if (!e) this.$set(this.temp, 'csmAddressId', this.row.csmAddressId)
        // this.$refs.dataForm.validateField(['csmName', 'csmAddressId'])
      },
      // 重置客户
      resetCsm() {
        this.$set(this.temp, 'csmName', '')
        this.$set(this.temp, 'csmAddressId', '')
        this.text = ''
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate(['csmName', 'csmAddressId'])
        })
      },
      success() {
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          const address = this.csmAddressList.find(item => item.csmAddressId === this.temp.csmAddressId)
          const params = {
            csmId: this.type === 'add' ? this.csmInfo.csmId : this.temp.csmId,
            insureCode: this.temp.insureCode,
            csmName: this.temp.csmName,
            insureStartDt: moment(this.temp.insureStartDt).format(),
            insureEndDt: moment(this.temp.insureEndDt).format(),
            insureAcc: this.temp.insureAcc,
            salePersonName: this.temp.salePersonName,
            remark: this.temp.remark,
            csmAddressId: this.temp.csmAddressId,
            csmAddress: address ? address.csmAddress : this.temp.csmAddressId
          }
          if (params.insureEndDt <= params.insureStartDt) {
            this.$message.error('生效日期不能大于截止日期')
            return
          }
          if (!params.insureAcc || params.insureAcc === 0) {
            this.$message.error('请输入投保金额')
            return
          }
          if (this.type === 'add') {
            this.add({
              ...params,
              primaryKey: this.temp.insureCode
            })
          } else {
            this.edit({
              ...params,
              ckOrgId: this.temp.ckOrgId,
              ckOrgName: this.temp.ckOrgName,
              ckOrgSNNo: this.temp.ckOrgSNNo,
              primaryKey: this.temp.preInsureCode
            })
          }
        })
      },
      async add(params) {
        await insureAdd(params)
        this.resolve()
        this.visible = false
        this.$notify({
          title: '提示',
          message: '新增成功',
          type: 'success',
          duration: 2000
        })
      },
      async edit(params) {
        await insureUpdate(params)
        this.resolve()
        this.visible = false
        this.$notify({
          title: '提示',
          message: '更新成功',
          type: 'success',
          duration: 2000
        })
      },
      inputFormat(e) {
        if (e.target.value) e.target.value = Number(e.target.value).toFixed(2)
      },
      reset() {
        this.type = 'add'
        this.temp = {
          insureCode: '',
          csmName: '',
          csmAddressId: '',
          insureAcc: undefined,
          salePersonName: '',
          insureStartDt: '',
          insureEndDt: '',
          remark: ''
        }
        this.text = ''
        this.csmInfo = null
        this.csmAddressList = []
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  & /deep/ .el-form-item {
    width: 48%;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
}
.info-title {
  display: flex;
  align-items: center;
  margin-top: 10px;
  margin-bottom: 20px;
  .title-icon {
    display: inline-block;
    width: 4px;
    height: 18px;
    margin-right: 6px;
    background: $themeColor;
  }
  span {
    font-weight: 700;
    color: $themeColor;
  }
}
</style>
